<?php

/**
 * 百大CRM sdk
 * @author chenshubo
 */
namespace App\Service\VendorClient\ShopBdCRM;
use App\Service\Code\Normal;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;
use Service\BaseService;

class ShopBdCRMApiClient extends BaseService
{
    protected $config;
    protected $router = [
        'vip_user_register'         => 'BFPLAT.CRM.VIP.REGISTER2',
        'vip_user_info'             => 'BFPLAT.CRM.VIP.CARDINFO2',
        'vip_user_update'           => 'BFPLAT.CRM.VIP.UPDATEINFO',
        'vip_user_ponits_buy'       => 'BFPLAT.CRM.VIP.BUYCENT',
        'vip_user_points_update'    => 'BFPLAT.CRM.VIP.UPDATECENT',
        'vip_user_points_log_query' => 'BFPLAT.CRM.VIP.SCOREITEM',
        'vip_user_coupon_send'      => 'BFPLAT.CRM.VIP.ISSUECODECOUPONS',
        'vip_user_coupon_info'      => 'BFPLAT.CRM.VIP.GETCOUPONCODE',
        'vip_user_cash_card_info'   => 'BFPLAT.CRM.VIP.GETCASHCARD',
        'vip_user_cash_card_frost'  => 'BFPLAT.CRM.VIP.PRETRANSCASHCARDPAYMENT',
        'vip_user_cash_card_pay'    => 'BFPLAT.CRM.VIP.CONTRANSCASHCARDPAYMENT',
        'vip_user_cash_card_cancel' => 'BFPLAT.CRM.VIP.CANTRANSCASHCARDPAYMENT',
        'vip_order_trade_create'    => 'BFPLAT.CRM.VIP.SAVERSALEBILLARTICLES',
        'vip_order_trade_pre_pay'   => 'BFPLAT.CRM.VIP.PRECHECKOUTBILL',
        'vip_order_trade_pay'       => 'BFPLAT.CRM.VIP.CONFIRMCHECKOUTBILL',
    ];
    
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 会员注册
     * @param array $param
     */
    public function vipUserRegister(array $body)
    {
        $param = $body['requestData'];
        if( empty($param['mobile']) ) {
            return Normal::returnCode(Normal::FAIL,"手机号码mobile不能为空");
        }
        
        if( empty($param['userName']) ) {
            return Normal::returnCode(Normal::FAIL,"会员名称userName不能为空");
        }
        
        if( empty($param['terminal']) ) {
            return Normal::returnCode(Normal::FAIL,"注册终端terminal不能为空");
        }
        
        $data = [
            'mobile'          => $param['mobile'],
            'vipName'         => $param['userName'],
            'birthday'        => $param['birthday'] ?? '',
            'gender'          => $param['gender'] ?? 0,
            'address'         => $param['address'] ?? '',
            'idcard_code'     => $param['idcardCode'] ?? '',
            'e_mail'          => $param['email'] ?? '',
            'openid'          => $param['openid'] ?? '',
            'vipfromId'       => (int)$param['terminal'],
            'storecode'       => $this->config['storecode'],
        ];
        return $this->execute('vip_user_register',$data);
    }
    
    /**
     * 会员信息查询
     * @param array $param
     */
    public function vipUserQuery(array $body)
    {
        $param = $body['requestData'];
        if( empty($param['condType']) ) {
            return Normal::returnCode(Normal::FAIL,"condType条件类型（1: 会员卡ID 2:卡号或者二维码内容3:手机号 4:车牌号）不能为空");
        }
        
        if( empty($param['condValue']) ) {
            return Normal::returnCode(Normal::FAIL,"condValue条件值不能为空");
        }
        
        $data = [
            'condType'  => $param['condType'],
            'condValue' => $param['condValue'],
        ];
        return $this->execute('vip_user_info',$data);
    }
    
    /**
     * 会员信息更新
     * @param array $param
     */
    public function vipUserUpdate(array $body)
    {
        $param = $body['requestData'];
        if( empty($param['vipId']) ) {
            return Normal::returnCode(Normal::FAIL,"vipId不能为空");
        }
        
        $data = [
            'vipId' => $param['vipId'],
        ];
        
        if( !empty($param['userName']) ) {
            $data['vipName'] = $param['userName'];
        }
        
        if( !empty($param['mobile']) ) {
            $data['mobile'] = $param['mobile'];
        }
        
        return $this->execute('vip_user_update',$data);
    }
    
    /**
     * 会员信息更新
     * @param array $param
     */
    public function vipUserPointsUpdate(array $body)
    {
        $param = $body['requestData'];
        if( empty($param['vipId']) ) {
            return Normal::returnCode(Normal::FAIL,"vipId不能为空");
        }
        
        if( empty($param['points']) ) {
            return Normal::returnCode(Normal::FAIL,"points积分不能为空[积分值(正数加积分，负数减积分)]");
        }
        
        if( empty($param['type']) ) {
            return Normal::returnCode(Normal::FAIL,"type不能为空[78：易购订单支付、79：易购活动赠送、80：易购订单退款 81：易购活动扣减、86：易购订单补赠]");
        }
        
        if( empty($param['billId']) ) {
            return Normal::returnCode(Normal::FAIL,"billId不能为空[流水单号]");
        }
        
        $types = [
            '78'    => '易购订单支付',
            '79'    => '易购活动赠送',
            '80'    => '易购订单退款',
            '81'    => '易购活动扣减',
            '86'    => '易购订单补赠'
        ];
        if( empty($types[$param['type']]) ) {
            return Normal::returnCode(Normal::FAIL,"积分类型不存在");
        }
        
        
        $data = [
            'vipId'         => $param['vipId'],
            'updateCent'    => $param['points'],
            'updateType'    => $param['type'],
            'storecode'     => $this->config['storecode'],
            'billId'        => $param['billId'],
            'brief'         => $types[$param['type']],
        ];
        
        if( !empty($param['Order_No']) ) {
            $data['Order_No'] = $param['Order_No'];
        }
        
        return $this->execute('vip_user_points_update',$data);
    }
    
    /**
     * 会员积分变动信息查询接口
     * @param array $param
     */
    public function vipUserPointsLogQuery(array $body)
    {
        $param = $body['requestData'];
        if( empty($param['vipId']) ) {
            return Normal::returnCode(Normal::FAIL,"vipId不能为空");
        }

        $data = [
            'vipId' => $param['vipId'],
        ];
        
        if( !empty($param['time_Begin']) ) {
            $data['time_Begin'] = $param['time_Begin'];
        }

        if( !empty($param['time_End']) ) {
            $data['time_End'] = $param['time_End'];
        }
        
        return $this->execute('vip_user_points_log_query',$data);
    }
    
    /**
     * 会员预付卡查询
     * @param array $param
     */
    public function vipUserCashCardInfo(array $body)
    {
        $param = $body['requestData'];
        
        if( empty($param['condType']) ) {
            return Normal::returnCode(Normal::FAIL,"condType预付卡信息方式查询不能为空");
        }
        
        if ( !in_array($param['condType'],['1','2']) ) {
            return Normal::returnCode(Normal::FAIL,"condTyp类型值必须要在1或2之间");
        }
        
        if( $param['condType'] == 2 && empty($param['password']) ) {
            return Normal::returnCode(Normal::FAIL,"password预付卡密码不能为空");
        }
        
        if( empty($param['condValue']) ) {
            return Normal::returnCode(Normal::FAIL,"condValue预付卡号码不能为空");
        }
        
        $data = [];
        $data['condType']   = $param['condType'];//条件类型（0：磁道，1: 会员卡ID 2:卡号）,目前只能根据预付卡号码来处理
        $data['condValue']  = $param['condValue'];
        if( $param['condType'] == 2 ) {
            $data['password']  = $param['password'];
        }
        $data['storecode'] = $this->config['storecode'];
        return $this->execute('vip_user_cash_card_info',$data);
    }
    
    /**
     * 会员预付卡使用冻结
     * 返回transId
     * @param array $param
     */
    public function vipUserCashCardFrost(array $body)
    {
        $param = $body['requestData'];
        if( empty($param['orderNo']) ) {
            return Normal::returnCode(Normal::FAIL,"orderNo订单号不能为空");
        }
        
        if( empty($param['isSale']) ) {
            return Normal::returnCode(Normal::FAIL,"isSale不能为空[是否是交易（1交易，-1退货）]");
        }
        
        if( empty($param['cashCardPayments']) ) {
            return Normal::returnCode(Normal::FAIL,"cashCardPayments券支付列表不能为空");
        }
        
        if( empty($param['passWord']) ) {
            return Normal::returnCode(Normal::FAIL,"passWord储值卡密码不能为空");
        }
        
        $data = [
            'storeCode'         => $this->config['storecode'],
            'posId'             => $this->config['posId'],
            'order_No'          => $param['orderNo'],
            'cashier'           => $this->config['cashier'],
            'passWord'          => $param['passWord'],
            'isSale'            => $param['isSale'],
            'accountDate'       => date("Y-m-d H:i:s"),
            'cashCardPayments'  => $param['cashCardPayments']
        ];
        return $this->execute('vip_user_cash_card_frost',$data);
    }
    
    /**
     * 会员预付卡使用确认
     * 返回transId
     * @param array $param
     */
    public function vipUserCashCardPayConfirm(array $body)
    {
        $param = $body['requestData'];
        if( empty($param['transId']) ) {
            return Normal::returnCode(Normal::FAIL,"transId交易ID不能为空[预付卡冻结接口返回的transId]");
        }
        
        if( empty($param['transMoney']) ) {
            return Normal::returnCode(Normal::FAIL,"transMoney交易金额不能为空");
        }
        
        $data = [
            'transId'       => $param['transId'],
            'transMoney'    => $param['transMoney'],
        ];
        return $this->execute('vip_user_cash_card_pay',$data);
    }
    
    /**
     * 会员预付卡使用取消
     * 返回transId
     * @param array $param
     */
    public function vipUserCashCardPayCancel(array $body)
    {
        $param = $body['requestData'];
        if( empty($param['transId']) ) {
            return Normal::returnCode(Normal::FAIL,"transId交易ID不能为空[预付卡冻结接口返回的transId]");
        }
        
        if( empty($param['transMoney']) ) {
            return Normal::returnCode(Normal::FAIL,"transMoney交易金额不能为空");
        }
        
        $data = [
            'transId'       => $param['transId'],
            'transMoney'    => $param['transMoney'],
        ];
        return $this->execute('vip_user_cash_card_cancel',$data);
    }
    
    /**
     * 会员交易订单上传商品
     * 返回transId
     * @param array $param
     */
    public function vipUserOrderTradeCreate(array $body)
    {
        $param = $body['requestData'];
        if( empty($param['vipId']) ) {
            return Normal::returnCode(Normal::FAIL,"vipId会员唯一标识符不能为空");
        }
        
        if( empty($param['orderNo']) ) {
            return Normal::returnCode(Normal::FAIL,"orderNo交易单号不能为空");
        }
        
        if( !isset($param['type']) ) {
            return Normal::returnCode(Normal::FAIL,"type交易类型不能为空[0销售 1 退货 2换货]");
        }
        
        if( empty($param['orderCreateTime']) ) {
            return Normal::returnCode(Normal::FAIL,"orderCreateTime消费时间不能为空");
        }
        
        if( empty($param['articleList']) ) {
            return Normal::returnCode(Normal::FAIL,"articleList商品列表不能为空");
        }
        
        if( !is_array($param['articleList']) ||  !is_array(current($param['articleList'])) ) {
            return Normal::returnCode(Normal::FAIL,"articleList商品列表必须为二维数组");
        }
        
        $data = [
            'vipId'             => $param['vipId'],
            'billId'            => $param['billId'] ?? 0,
            'storeCode'         => $this->config['storecode'],
            'posId'             => $this->config['posId'],
            'orderNo'           => $param['orderNo'],
            'type'              => $param['type'],
            'accountDate'       => date("Y-m-d H:i:s"),
            'cashier'           => $this->config['cashier'],
            'shoppingTime'      => $param['orderCreateTime'],
            'originalPosId'     => $this->config['posId'],
            'articleList'       => $param['articleList'],
        ];
        if($param['type'] != 0){
            $data["originalOrderNo"] = $param['originalOrderNo'];
        }
        return $this->execute('vip_order_trade_create',$data);
    }
    
    /**
     * 会员交易准备结账
     * 返回transId
     * @param array $param
     */
    public function vipUserOrderTradePreparePay(array $body)
    {
        $param = $body['requestData'];
        if( empty($param['serverBillId']) ) {
            return Normal::returnCode(Normal::FAIL,"serverBillId消费记录id不能为空");
        }
        
        if( empty($param['paymentList']) ) {
            return Normal::returnCode(Normal::FAIL,"paymentList支付方式列表不能为空");
        }

        if( !is_array($param['paymentList']) ||  !is_array(current($param['paymentList'])) ) {
            return Normal::returnCode(Normal::FAIL,"paymentList支付方式列表必须为二维数组");
        }
        
        $data = [
            'serverBillId'  => $param['serverBillId'],
            'paymentList'   => $param['paymentList'],
            'accountDate'   => date("Y-m-d H:i:s"),
        ];
        return $this->execute('vip_order_trade_pre_pay',$data);
    }
    
    /**
     * 会员交易结账
     * 返回transId
     * @param array $param
     */
    public function vipUserOrderTradePay(array $body)
    {
        if( empty($body['serverBillId']) ) {
            return Normal::returnCode(Normal::FAIL,"serverBillId消费记录id不能为空");
        }
        $data = [
            'serverBillId'  => $body['serverBillId'],
        ];
        return $this->execute('vip_order_trade_pay',$data);
    }
    
    /**
     * 钱买分接口
     * @param array $param
     */
    public function tradeBuyPoints(array $body)
    {
        $param = $body['requestData'];
        if( empty($param['vipId']) ) {
            return Normal::returnCode(Normal::FAIL,"vipId不能为空");
        }
        
        if( empty($param['points']) ) {
            return Normal::returnCode(Normal::FAIL,"points不能为空");
        }
        
        if( empty($param['money']) ) {
            return Normal::returnCode(Normal::FAIL,"money不能为空");
        }
        
        $data = [
            'vipId'           => $param['vipId'],
            'centToBuy'       => $param['points'],
            'cashMoney'       => $param['money'],
            'storecode'       => $this->config['storecode'],
            'posId'           => $this->config['posId'],
            'cashier'         => $this->config['cashier'],
            'accountDate'     => date("Y-m-d H:i:s")
        ];
        return $this->execute('vip_user_ponits_buy',$data);
    }
    
    /**
     * 签名
     * @param string $method
     * @param array $data
     */
    protected function getSign(string $method,array $data)
    {
        $data = [
            'timestamp' => date("Y-m-d H:i:s"),
            'format'    => 'json',
            'data'      => json_encode($data)
        ];
        $json = json_encode($data,JSON_UNESCAPED_UNICODE);
        $str = $this->config['appsecret'].$json.$this->config['appsecret'];
        $data['verifycode'] = strtoupper(md5($str));
        return $data;
    }
    
    /**
     * 执行请求
     * @param string $method
     * @param array $param
     * @return unknown[]|string[]|array[]
     */
    public function execute(string $method,array $data)  
    {
        if(empty($data) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        
        $op = $this->router[$method];
        $sign_data = $this->getSign($op, $data);
        if( in_array($method,['vip_user_cash_card_info','vip_user_cash_card_frost','vip_user_cash_card_pay','vip_user_cash_card_cancel']) ) {
            $url = $this->config['cashCardURL'];
        } else {
            $url = $this->config['userURL'];
        }
        
        $url  = "{$url}/api?source={$this->config['source']}&dest={$this->config['dest']}&op={$op}&verifycode={$sign_data['verifycode']}";
        $data = [
            'timestamp'     => $sign_data['timestamp'],
            'format'        => $sign_data['format'],
            'data'          => $sign_data['data']
        ];
        $parameter = [
             [
                'tag'       => 'bd_crm_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $data,
                'method'    => 'post',
                'format'    => 'json',
                'header'    => [
                    "Content-Type:application/json",
                ],
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = @json_decode($res, true);
        if( isset($resHttp['RetCode']) && $resHttp['RetCode'] == '0' ) {
            return Normal::returnCode(Normal::SUC,"百大CRM服务接口操作成功",$resHttp["data"]);
        }
        $message = isset($resHttp['RetMsg']) ? $resHttp['RetMsg'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,"百大CRM服务接口操作失败：{$message}");
    }
}